//
//  SINAHelpFeedbackViewController.m
//  PlanTech
//
//  Created by ruifeng song on 2018/5/25.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINAHelpFeedbackViewController.h"
#import <WebKit/WebKit.h>
#import "SINAStringUtils.h"

@interface SINAHelpFeedbackViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
{
    
}
@property(nonatomic,strong) WKWebView * webView;
@property(nonatomic,strong)UIProgressView * progressView;

@end

@implementation SINAHelpFeedbackViewController
{
    NSMutableArray * arr ;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //OC注册供JS调用的方法
    [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"submitData"];
    [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"sendImagesArr"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"submitData"];
     [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"sendImagesArr"];
}
- (void)dealloc {
    DLog(@"SINAHelpFeedbackViewController dealloc");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"帮助与反馈";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.webView];
    
    NSString * urlStr = nil;
    
    if (self.helpFeedbackType == SINAHELPFEEDBACK_STUDENT_TYPE) {
        urlStr = [NSString stringWithFormat:@"%@%@",baseUrlFeedBack,student_feedbackhelp];
    }
    else
    {
        urlStr = [NSString stringWithFormat:@"%@%@",baseUrlFeedBack,teacher_feedbackhelp];
    }
    
    DLog(@"%@",urlStr);
  
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",urlStr]]]];

    //添加KVO监听
    [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    //添加进度条
    self.progressView = [[UIProgressView alloc]init];
    self.progressView.frame = self.view.bounds;
    [self.view addSubview:self.progressView];
    self.progressView.backgroundColor = [UIColor greenColor];
}

- (WKWebView *)webView {
    if (!_webView) {
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [WKUserContentController new];
        
        WKPreferences *preferences = [WKPreferences new];
        //在iOS 上默认为NO,表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 12.0;
        configuration.preferences = preferences;
        
        //web内容处理池
        configuration.processPool = [[WKProcessPool alloc]init];
        
        SINAUserModel *userModel = [[SINACommonUserHelper share] getUserModel];
        
        NSString * name = userModel.userRealName;
        NSString * university =  userModel.universityName;
        NSString *college = userModel.collegeName;
        NSString * phone = userModel.userPhone;
        NSString * avatar = userModel.userTitleImageUrl;
        
        //将所有cookie以document.cookie = 'key=value'；形式进行拼接
        NSString * cookieValue = [NSString stringWithFormat:@"document.cookie = 'name=%@';document.cookie = 'avatar=%@';document.cookie = 'university=%@';document.cookie = 'college=%@';document.cookie = 'phone=%@'",[self encodeToPercentEscapeString:name],avatar,[self encodeToPercentEscapeString:university],[self encodeToPercentEscapeString:college],phone];
        WKUserScript * cookieScrpit = [[WKUserScript alloc]initWithSource:cookieValue injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [configuration.userContentController addUserScript:cookieScrpit];
        
        CGRect frame = CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        _webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _webView.backgroundColor = [UIColor clearColor];
        _webView.scrollView.backgroundColor = [UIColor clearColor];
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        
        
    }
    return _webView;
}

- (NSString *)encodeToPercentEscapeString: (NSString *) input

{
    
    NSString *outputStr = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                       
                                                                                       NULL, /* allocator */
                                                                                       
                                                                                       (__bridge CFStringRef)input,
                                                                                       
                                                                                       NULL, /* charactersToLeaveUnescaped */
                                                                                       
                                                                                       (CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8);
    
    return
    
    outputStr;
    
}

#pragma mark -KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"loading"]) {
        DLog(@"loading");
    }
    else if ([keyPath isEqualToString:@"title"])
    {
        //        self.navigationItem.title = self.webView.title;
    }
    else if([keyPath isEqualToString:@"estimatedProgress"])
    {
//        DLog(@"progress : %f",self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
    }
    
    if (!self.webView.loading) {
        [UIView animateWithDuration:0.5 animations:^{
            
            self.progressView.alpha = 0;
        }];
    }
}

-(void)goback
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
}

-(void)gofarward
{
    if ([self.webView canGoForward]) {
        [self.webView goForward];
    }
}

-(void)dismiss
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
    else
    {
        [super dismiss];
    }
}

#pragma mark -WKScriptMessageHandler
//通过这个方法获取 JS 传来的json字符串
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"sendImagesArr"]) {
        
        NSArray * imgs = message.body;
        
//        DLog(@"imgs = %ld",imgs.count);
        
        arr = [NSMutableArray array];
        for (NSString * dataString in imgs) {
            NSData * data = [NSData dataWithBase64EncodedString:dataString];
            UIImage * img = [UIImage imageWithData:data];
            
            UIImage * img1 = [self scaleImage:img toScale:0.5];
            
            [arr addObject:img1];
        }
    }
    
    if ([message.name isEqualToString:@"submitData"]) {
        
        if (arr!=nil && arr.count > 0) {
            
            [self submitFeedBackImgs:arr imgsUrl:^(NSString * obj) {
               
                if (obj!=nil) {
                    [self submitFeedBackWithBody:message.body imgs:obj];
                }
            }];
        }
        else
        {
            [self submitFeedBackWithBody:message.body imgs:nil];
        }
    }

}

-(void)submitFeedBackImgs:(NSArray *)imgArr imgsUrl:(void(^)(NSString * ))imgsUrl
{
    [self startLoading];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostFileRequestWithParamters:nil withImageArray:arr success:^(id responseData) {
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            NSArray *imageArray = responseData[@"content"];
            if (imageArray!=nil&&imageArray.count>=1) {
                
                NSString *imgs = [imageArray componentsJoinedByString:@","];
                DLog(@"titleImageUrl  === %@",imgs);
                imgsUrl(imgs);
            }else{
                WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"提交失败" sureBtn:@"确定"
                                                                     cancleBtn:nil];
                [alertView showXLAlertView];
                
                imgsUrl(nil);
            }
        }
    } failure:^(NSError *error, NSInteger code) {
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"提交失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        
         imgsUrl(nil);
    }];
}

-(void)submitFeedBackWithBody:(NSString *)body imgs:(NSString *)imgs
{
    NSDictionary *contentJson = [SINAStringUtils dictionaryWithJsonString:body];
    
//    DLog(@"%@",contentJson);
    
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",baseUrlFeedBack,[contentJson objectForKey:@"url"]];
    NSMutableDictionary * par = [[NSMutableDictionary alloc]init];
    
    for (NSString * key  in contentJson.allKeys) {
        if (key!=nil && ![key isEqualToString:@""] && ![key isEqualToString:@"url"]) {
            [par setObject:[contentJson objectForKey:key] forKey:key];
        }
    }
    
    if (imgs!=nil && ![imgs isEqualToString:@""] && imgs.length > 0) {
        
        [par setObject:imgs forKey:@"images"];
    }
    
//    DLog(@"par === %@",par);
    NSMutableDictionary * sjDic = [NSMutableDictionary dictionary];
    [sjDic setValue:[SINAHttpRequestUtils encodeDicParams:par] forKey:@"sj"];
    [self startLoading];
    
    [CXAFNHttpRequestUtils httpPostRequest:urlStr withParamters:sjDic success:^(id responseData) {
        WeakSelf;
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:@"已提交" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                 [weakSelf dismiss];
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
            
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        WeakSelf;
        [weakSelf stopLoading];
        
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:nil message:@"提交失败" sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
        
    }];
}

#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

#pragma mark -WKNavigationDelegate method
//页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    
}

//当内容开始返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

//页面加载完成之后调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    DLog(@"66 ==== %s",__FUNCTION__);
    
    //禁用选中效果
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
}

//页面加载失败时调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    
}

//接收到服务器跳转请求之后调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}

//在收到响应后，决定是否跳转
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler
{
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    
    //不允许跳转
    //    decisionHandler(WKNavigationResponsePolicyCancel);
}

//在发送请求之前，决定是否跳转
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated && ![hostname containsString:@"baodaoapp.com"]) {
        //对于跨域，需要手动跳转 ，  用系统浏览器（Safari）打开
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        
        //不允许web内跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else
    {
        self.progressView.alpha = 1.0;
        
        //允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

#pragma mark - WKUIDelegate method
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    return [[WKWebView alloc]init];
}

//输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.textColor = [UIColor redColor];
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler([[alert.textFields lastObject]text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}

//确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
    UIAlertController  *alert  = [UIAlertController alertControllerWithTitle:@"confirm" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(YES);
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
    DLog(@"%@",message);
    
}

//警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"alert" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
    DLog(@"%@",message);
}

//#pragma mark - private method
//-(void)handleCustomAction:(NSURL *)url
//{
//    NSString * host = [url host];
//
//    DLog(@"%@",host);
//
//}
//
////获取图片
//-(void)beginOpenPhoto
//{
//    dispatch_async(dispatch_get_main_queue(), ^{
//
//        [self takePhoto];
//    });
//}
//
//#pragma mark 取消选择照片代理方法
//-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
//{
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}
//
//#pragma mark    //打开本地照片
//-(void) localPhoto
//{
//    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
//    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    imagePicker.delegate = self;
//    [self presentViewController:imagePicker animated:YES completion:nil];
//}
//
//#pragma mark  打开相机拍照
//-(void)takePhoto
//{
//    UIImagePickerControllerSourceType sourceType =UIImagePickerControllerSourceTypeCamera;
//    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
//        picker.delegate = self;
//        picker.allowsEditing = YES;
//        picker.sourceType = sourceType;
//        picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//        [self presentViewController:picker animated:YES completion:nil];
//    }
//    else
//    {
//        DLog(@"模拟器中不能打开相机");
//        [self localPhoto];
//    }
//}
//
////选择一张照片后进入这里
//-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
//{
//    NSString * type = [info objectForKey:UIImagePickerControllerMediaType];
//
//    //当前选择的类型是照片
//    if ([type isEqualToString:@"public.image"]) {
//
//        //获取照片
//        UIImage * getImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//        DLog(@"=== Decoded image size :%@",NSStringFromCGSize(getImage.size));
//
//        NSString * imagePath = @"";
//        /**
//         *  这里是IOS 调用 js 其中setImageWithPath 就是js 中的方法 setImageWithPath(),参数是字典
//         */
//        NSString * callJSString = [NSString stringWithFormat:@"%@({\"imagePath\":\"%@\",\"iosContent\":\"获取图片成功，把系统获取的图片路径传给js 让html显示\"})",@"setImageWithPath",imagePath];
//
//        [self.webView evaluateJavaScript:callJSString completionHandler:^(id obj, NSError * _Nullable error) {
//
//            if (!error) {
//                DLog(@"OC调 JS成功");
//            }
//            else
//            {
//                DLog(@"OC 调 JS失败");
//            }
//        }];
//
//        [picker dismissViewControllerAnimated:YES completion:nil];
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
